#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

#define PATHNAME "/home/ubuntu/blog-code" //路径名

#define PROJ_ID 0x6666 //整数标识符
#define SIZE 4096 //共享内存的大小

int main()
{
    //1.ftok函数做key
    key_t key = ftok(PATHNAME,PROJ_ID);
    if(key < 0) 
    {
        perror("key");
        return 1;
    }
    //2.shmget制造共享内存
    int shmid = shmget(key,SIZE,IPC_CREAT | IPC_EXCL | 0666);
    if(shmid < 0)
    {
        perror("shmid");
        return 1;
    }
    printf("key:%x\n",key);
    printf("shmid:%d\n",shmid);
    //3.shmat关联共享内存
    printf("attach begin\n");
    sleep(2);
    //以读写打开共享内存
    char* mem = shmat(shmid,NULL,SHM_RDONLY);
    if(mem == (void*)-1)
    {
        perror("shmat");
        return 1;
    }
    printf("attach end\n");
    sleep(2);
    //4.释放共享内存
    shmctl(shmid,IPC_RMID,NULL);
    return 0;
}